<template>
  <div class="dashboard-container">
    <!-- 1. 数据总览 -->
    <div class="box-padding-16">
      <div class="box-padding-16-flex">
        <div class="box-padding-16-flex-left">
          <div class="line"></div>
          <div class="box-title">数据总览</div>
          <div class="box-subtitle">{{ getCurrentDateTime() }} 更新</div>
        </div>
        <div class="times">
          <el-date-picker v-model="paramsQuery.yearMonth" type="month" @change="selectTime" format="yyyy-MM"
            value-format="yyyy-MM" placeholder="选择日期" />
        </div>
      </div>
      <div class="card-wrap">
        <el-row :gutter="20" class="card-row">
          <el-col class="card-col" :span="6" v-for="(item, index) in productionData" :key="index">
            <div class="production-card" :style="{ background: item.bgColor }">
              <div class="production-tops">
                <div>
                  <div>{{ item.title }}</div>
                  <div class="value-display">{{ item.value }}万吨</div>
                </div>
                <div class="progress-wrapper" v-if="item.showProgress">
                  <el-progress type="circle" stroke-linecap="butt" :show-text="false"
                    :percentage="item.progressPercentage" :width="65" :stroke-width="8" :color="item.progressColor" />
                </div>
              </div>
              <div class="detail">
                <template v-if="item.detail">
                  <div class="last-value">
                    {{ item.detail.lastTitle }}：{{ item.detail.lastValue ? item.detail.lastValue : 0 }}万吨
                  </div>
                  <div class="mom-ratio">环比 {{ item.momRatio }}%</div>
                </template>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <el-row class="card-row-warp">
      <el-col :span="18">
        <!-- 2. 本月产量分布 -->
        <div class="box-padding-16 chart-area">
          <div class="box-padding-16-flex">
            <div class="box-padding-16-flex-left">
              <div class="line"></div>
              <div class="box-title">本月产量分布</div>
            </div>
          </div>

          <!-- 图表区 -->
          <div class="chart-flex-box">
            <div class="left-bar-box" ref="leftBar">
              <div id="barChart" class="chart-box"></div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <!-- 2. 本月产量分布 -->
        <div class="box-padding-16 chart-area box-padding-none">
          <div class="box-padding-16-flex">
            <div class="box-padding-16-flex-left">
              <div class="line"></div>
              <div class="box-title">本月产量分布</div>
            </div>
          </div>

          <!-- 图表区 -->
          <div class="chart-flex-box">
            <div class="right-pies-box" ref="rightPies">
              <div class="pie-item">
                <div class="chart-title">本月各产品产量分布</div>
                <div id="monthPieChart" class="chart-box"></div>
              </div>
              <div class="pie-item">
                <div class="chart-title">昨日各产品产量分布</div>
                <div id="yesterdayPieChart" class="chart-box"></div>
              </div>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  compare,
  quarter,
  monthCompare,
  dayCompare,
  barDataDynamic,
  pieData,
  pieDataYesterday,
} from "@/api/home.js";
export default {
  data() {
    return {
      paramsQuery: {
        yearMonth:
          new Date().getFullYear() +
          "-" +
          (new Date().getMonth() + 1).toString().padStart(2, "0"),
      },
      productionData: [
        {
          title: "昨日产量",
          value: "4.34",
          bgColor: "linear-gradient(351.54deg, #9666F7 -7.1%, #B38FFA 93.49%)",
          detail: { lastTitle: "前日产量", lastValue: "25.46" },
          progressColor: "#8450c4",
          progressPercentage: 68,
          showProgress: true,
          momRatio: "12.53%",
        },
        {
          title: "本月产量",
          value: "20.34",
          bgColor: "linear-gradient(351.54deg, #0AD0A1 -7.1%, #69D488 93.49%)",
          detail: { lastTitle: "上季度产量", lastValue: "25.46" },
          showProgress: true,
          progressPercentage: 68,
          progressColor: "#20B2AA",
          momRatio: "12.53%",
        },
        {
          title: "本季产量",
          value: "58.34",
          bgColor: "linear-gradient(349.2deg, #02ADED 6.47%, #21DCFA 91.94%)",
          detail: { lastTitle: "上月产量", lastValue: "25.46" },
          progressColor: "rgb(34,162,231)",
          momRatio: "12.53%",
          progressPercentage: 68,
          showProgress: true,
        },
        {
          title: "本年产量",
          value: "293.34",
          bgColor: "linear-gradient(351.54deg, #4468FD -7.1%, #49ADFF 93.49%)",
          detail: { lastTitle: "去年产量", lastValue: "293.46" },
          showProgress: true,
          progressPercentage: 68,
          progressColor: "#5070DD",
          momRatio: "12.53%",
        },
      ],
      chartData: {
        barData: {
          xAxis: Array.from({ length: 30 }, (_, i) => i + 1),
          series: [
            {
              name: "全部",
              type: "bar",
              data: this.generateRandomData(30, 6, 10),
            },
            {
              name: "5-10",
              type: "bar",
              data: this.generateRandomData(30, 4, 8),
            },
            {
              name: "10-20",
              type: "bar",
              data: this.generateRandomData(30, 5, 9),
            },
            {
              name: "20-30",
              type: "bar",
              data: this.generateRandomData(30, 6, 8),
            },
            {
              name: "机制砂",
              type: "bar",
              data: this.generateRandomData(30, 7, 9),
            },
          ],
          colors: ["#1890ff", "#00c896", "#52c41a", "#faad14", "#fa8c16"],
        },
        // 修改为接口数据，移除默认值
        pieData: {
          month: { data: [] },
          yesterday: { data: [] },
          colors: ["#1890ff", "#00c896", "#52c41a", "#faad14"],
        },
      },
      gradientColors: [
        // 原有配色
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FAB2FF" },
            { offset: 1, color: "#5644FF" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#7AECF8" },
            { offset: 1, color: "#48DE94" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FEA492" },
            { offset: 1, color: "#FF4C52" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#A5A1FF" },
            { offset: 1, color: "#1F90FF" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "rgba(81, 85, 198, 1)" },
            { offset: 1, color: "rgba(81, 85, 198, .6)" },
          ],
        },
        // 新增12条匹配配色
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FF4D9E" },
            { offset: 1, color: "#9B5DE5" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#00F5FF" },
            { offset: 1, color: "#00A896" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FFE066" },
            { offset: 1, color: "#F48C06" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#4CC9F0" },
            { offset: 1, color: "#3A0CA3" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#52B788" },
            { offset: 1, color: "#2D6A4F" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FF6B6B" },
            { offset: 1, color: "#C1121F" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "rgba(72, 191, 227, 1)" },
            { offset: 1, color: "rgba(30, 58, 138, 0.7)" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#F15BB5" },
            { offset: 1, color: "#7209B7" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#90E0EF" },
            { offset: 1, color: "#0077B6" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FFF3B0" },
            { offset: 1, color: "#F77F00" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "rgba(86, 68, 255, 0.9)" },
            { offset: 1, color: "rgba(25, 25, 112, 0.5)" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FF006E" },
            { offset: 1, color: "#9D0208" },
          ],
        },
      ],
    };
  },
  methods: {
    getCurrentDateTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      return `${year}/${month}/${day} ${hours}:${minutes}`;
    },
    selectTime() {
      this.loadAlldata();
      this.initBarChart();
      this.initPieChart("monthPieChart", this.chartData.pieData.month.data);
      this.initPieChart(
        "yesterdayPieChart",
        this.chartData.pieData.yesterday.data
      );
    },
    loadAlldata() {
      compare(this.paramsQuery).then((res) => {
        this.productionData[3].progressPercentage = res.data.growthRate;
        this.productionData[3].momRatio = res.data.growthRate;
        this.productionData[3].value = res.data.thisYearProduction;
        this.productionData[3].detail.lastValue = res.data.lastYearProduction;
      });
      quarter(this.paramsQuery).then((res) => {
        this.productionData[2].progressPercentage = res.data.growthRate;
        this.productionData[2].momRatio = res.data.growthRate;
        this.productionData[2].value = res.data.thisQuarterProduction;
        this.productionData[2].detail.lastValue = res.data.lastQuarterProduction;
      });
      monthCompare(this.paramsQuery).then((res) => {
        this.productionData[1].progressPercentage = res.data.growthRate;
        this.productionData[1].momRatio = res.data.growthRate;
        this.productionData[1].value = res.data.thisYearProduction;
        this.productionData[1].detail.lastValue = res.data.lastYearProduction;
      });
      dayCompare(this.paramsQuery).then((res) => {
        this.productionData[0].progressPercentage = res.data.growthRate;
        this.productionData[0].momRatio = res.data.growthRate;
        this.productionData[0].value = res.data.yesterdayProduction;
        this.productionData[0].detail.lastValue = res.data.lastYearProduction;
      });
    },
    generateRandomData(len, min, max) {
      return Array.from({ length: len }, () =>
        Number((Math.random() * (max - min) + min).toFixed(1))
      );
    },
    processChartData(rawData) {
      const dateMap = {};
      const typeSet = new Set();
      rawData.forEach((item) => {
        const day = new Date(item.date).getDate().toString().padStart(2, "0");
        const type = item.type;
        if (!dateMap[day]) dateMap[day] = {};
        dateMap[day][type] = item.value;
        typeSet.add(type);
      });

      // 直接获取keys，不排序
      const xAxis = Object.keys(dateMap); // 移除 .sort()

      const series = [];
      Array.from(typeSet).forEach((type) => {
        const data = xAxis.map((day) => dateMap[day][type] || 0);
        series.push({
          name: type,
          type: "bar",
          data: data,
          barWidth: 8,
          itemStyle: {
            borderRadius: [2, 2, 0, 0],
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: this.gradientColors[series.length % this.gradientColors.length].colorStops[0].color },
              { offset: 1, color: this.gradientColors[series.length % this.gradientColors.length].colorStops[1].color }
            ])
          },
        });
      });
      return { xAxis, series };
    },
    initBarChart() {
      barDataDynamic(this.paramsQuery).then((res) => {
        const processedData = this.processChartDataCopy(res.data)
        const data = this.processChartDataLast(processedData)
        const chart = echarts.init(document.getElementById("barChart"));
        chart.setOption(this.getProductionBarOption(data))
      });
    },
    processChartDataCopy(rawData) {
      return Object.values(
        rawData.reduce((acc, item) => {
          const day = item.date.split('/')[2];
          if (!acc[day]) {
            acc[day] = { month: day, equipmentList: [] };
          }
          acc[day].equipmentList.push({
            name: item.type,
            value: item.value
          });
          return acc;
        }, {})
      );
    },
    getProductionBarOption(data) {
      const equipmentCount = data.equipment.length;
      let barWidth;
      if (equipmentCount <= 4) {
        barWidth = 30;
      } else if (equipmentCount <= 8) {
        barWidth = 20;
      } else {
        barWidth = 12;
      }

      return {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          formatter: function (params) {
            return params
              .map((p) => `${p.marker} ${p.seriesName}: ${p.value}万吨`)
              .join("<br/>");
          },
        },
        legend: {
          data: data.equipment,
          top: "5%",
          icon: "circle",
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 12,
          textStyle: { fontSize: 12 },
          type: equipmentCount > 8 ? "scroll" : "plain",
          pageIconSize: 12,
          pageButtonItemGap: 5,
          selected: data.equipment.reduce((acc, name, index) => {
            acc[name] = index < 4;
            return acc;
          }, {}),
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "10%",
          containLabel: true,
          top: equipmentCount > 8 ? "20%" : "15%",
        },
        xAxis: {
          type: "category",
          data: data.months,
          axisTick: { alignWithLabel: true },
        },
        yAxis: {
          type: "value",
          name: "万吨",
          nameTextStyle: { padding: [0, 0, 0, -40] },
        },
        series: data.equipment.map((name, index) => ({
          name,
          type: "bar",
          data: data.equipmentData[index],
          barWidth: barWidth,
          barCategoryGap: equipmentCount > 8 ? "60%" : "80%",
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: this.gradientColors[index % 17].colorStops[0].color,
              },
              {
                offset: 1,
                color: this.gradientColors[index % 17].colorStops[1].color,
              },
            ]),
            borderRadius: [3, 3, 0, 0],
          },
          emphasis: {
            focus: "series",
            blurScope: "coordinateSystem",
          },
        })),
      };
    },
    processChartDataLast(rawData) {
      const monthMap = new Map();
      const equipMap = new Map();

      rawData.forEach(({ month, equipmentList }) => {
        monthMap.set(month, month.slice(-2) + "日");
        equipmentList.forEach(({ name }) => equipMap.set(name, name));
      });

      const months = Array.from(monthMap.keys())
        .sort((a, b) => a.localeCompare(b))
        .map((m) => monthMap.get(m));

     const equipment = Array.from(equipMap.keys()).sort((a, b) => {
  // "全部"始终排在最前面
  if (a === '全部') return -1;
  if (b === '全部') return 1;
  // 其他项按字母顺序排序
  return a.localeCompare(b, 'zh-CN');
});
      const equipmentData = equipment.map(() =>
        Array(months.length).fill(null)
      );

      rawData.forEach(({ month, equipmentList }) => {
        const mIndex = months.findIndex((m) =>
          m.endsWith(month.slice(-2) + "日")
        );
        equipmentList.forEach(({ name, value }) => {
          const eIndex = equipment.findIndex((e) => e === name);
          if (eIndex !== -1 && mIndex !== -1) {
            equipmentData[eIndex][mIndex] = value;
          }
        });
      });

      return { months, equipment, equipmentData };
    },



    // 修改后的initPieChart方法
    initPieChart(id, data) {
      const processData = (rawData) =>
        rawData.map((item) => ({ value: item.value, name: item.type }));

      // 立即初始化图表（初始数据为空数组）
      const chart = echarts.init(document.getElementById(id));
      if (id === "monthPieChart") this.monthChart = chart;
      if (id === "yesterdayPieChart") this.yesterdayChart = chart;

      const createSeries = (data) => data.map((item, index) => {
        const colorIndex = index % this.gradientColors.length;
        return {
          value: item.value,
          name: item.name,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: this.gradientColors[colorIndex].colorStops[0].color },
              { offset: 1, color: this.gradientColors[colorIndex].colorStops[1].color }
            ])
          }
        };
      });

      // 初始渲染（使用传入的数据，初始为空数组）
      chart.setOption({
        tooltip: {
          trigger: "item",
          formatter: `{b}: {c}万吨`,
        },
        legend: {
          orient: 'horizontal',
          bottom: 0,
          left: 'center',
          icon: 'circle',
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 12,
          textStyle: { fontSize: 12 }
        },
        series: [
          {
            type: "pie",
            radius: ["40%", "70%"],
            center: ["60%", "50%"],
            label: {
              formatter: "{b}\n{c}万吨",
              rich: {
                a: {
                  fontSize: 14,
                  lineHeight: 20,
                },
              },
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 15,
              smooth: true,
            },
            itemStyle: {
              borderWidth: 2,
              borderColor: '#fff'
            },
            emphasis: {
              label: { show: true, fontSize: 14, fontWeight: "bold" },
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.3)",
              },
            },
            data: createSeries(data),
            radius: '50%',
          },
        ],
      });

      // 根据图表ID调用对应接口并更新数据
      const apiCall = id === "monthPieChart"
        ? pieData(this.paramsQuery)
        : pieDataYesterday(this.paramsQuery);

      apiCall.then((res) => {
        const processedData = processData(res.data);

        // 更新data中的数据
        if (id === "monthPieChart") {
          this.chartData.pieData.month.data = processedData;
        } else {
          this.chartData.pieData.yesterday.data = processedData;
        }

        // 使用接口数据更新图表
        chart.setOption({
          series: [{
            data: createSeries(processedData)
          }]
        });
      });
    },
    handleResize() {
      const leftH = this.$refs.leftBar?.clientHeight;
      if (leftH && this.$refs.rightPies) {
        this.$refs.rightPies.style.height = leftH + "px";
      }

      this.barChart?.resize();
      this.monthChart?.resize();
      this.yesterdayChart?.resize();
    }
  },
  created() {
    this.loadAlldata();
  },
  mounted() {
    this.initBarChart();
    this.initPieChart("monthPieChart", this.chartData.pieData.month.data);
    this.initPieChart("yesterdayPieChart", this.chartData.pieData.yesterday.data);

    this.handleResize();
    window.addEventListener("resize", this.handleResize);

    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.handleResize);
      this.barChart?.dispose();
      this.monthChart?.dispose();
      this.yesterdayChart?.dispose();
    });
  }
};
</script>

<style scoped lang="scss">
.box-padding-16.chart-area {
  display: flex;
  flex-direction: column;
  flex: 1;
  margin-top: 0;
}

.box-padding-none {
  margin-left: 0 !important;
  width: calc(100% - 16px);
}

.card-row-warp {
  flex: 1;

  .el-col {
    height: 100%;
    display: flex;
    flex-direction: column;
  }
}

/* 图表区：抵消父级 padding，重新占满整屏剩余高度 */
.box-padding-16.chart-area .chart-flex-box {
  flex: 1;
  width: calc(100% + 32px);
  height: calc(100% + 32px);
  margin: -16px;
  padding: 12px 20px 20px;
  box-sizing: border-box;
}

/* 饼图容器：提前吃掉标题高度，防止底部留空 */
.box-padding-16.chart-area .pie-item {
  padding-top: 32px;
  box-sizing: border-box;
}

.box-padding-16.chart-area .chart-title {
  position: absolute;
  left: calc((100% - 130px) / 2);
  top: 20px;
  width: 130px;
  font-size: 14px;
  font-weight: 500;
  background: #fff;
  z-index: 1;
}

.box-padding-16.chart-area .chart-box {
  width: 100%;
  height: 100%;
  padding-top: 0;
  box-sizing: border-box;
}

/* =================  以下样式均保持原样  ================= */
html,
body {
  margin: 0;
  height: 100%;
}

.times {
  width: 120px;
  height: 24px;
  display: flex;
  align-items: center;
}

.times ::v-deep .el-input__inner {
  width: 120px !important;
  height: 24px !important;
  line-height: 24px !important;
  padding-top: 0 !important;
  padding-bottom: 0 !important;
  border-radius: 30px;
  background: rgba(243, 247, 251, 1);
}

.times ::v-deep .el-input__icon {
  line-height: 24px;
}

.dashboard-container {
  height: calc(100vh - 60px);
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  overflow: hidden;
}

.card-wrap {
  margin-top: 16px;
}

.card-row {
  margin: 0 -10px;
  display: flex;
  flex-wrap: nowrap;
  gap: calc(20 / 1920 * 100vw);
}

/* 列：等分剩余宽度 */
.card-col {
  flex: 1 0 0%;
  min-width: 0;
  padding: 0 !important;
  /* 先不设最小宽度，由媒体查询接管 */
}

.production-card {
  height: 140px;
  //padding: 15px 20px;
  color: #fff;
  padding: 18px calc(28 / 1920 * 100vw);
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.production-tops {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 5px;
}

.value-display {
  font-size: 24px;
  font-weight: bold;
  margin: 0;
  margin-top: 10px;
}

.detail {
  font-size: 12px;
  display: flex;
  justify-content: space-between;
}

.chart-flex-box {
  flex: 1;
  display: flex;
  padding: 12px 20px 20px;
  gap: 20px;
  overflow: hidden;
}

.left-bar-box,
.right-pies-box {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.left-bar-box {
  flex: 3;
}

.right-pies-box {
  flex: 1;
  gap: 8px;
}

.pie-item {
  flex: 1;
  position: relative;
  background: #fff;
  border-radius: 5px;
}

.chart-box {
  height: 100%;
  width: 100%;
  padding-top: 32px;
  box-sizing: border-box;
}

@media (max-width: 1200px) {
  .chart-flex-box {
    flex-direction: column;
  }

  .left-bar-box,
  .right-pies-box {
    width: 100%;
  }
}
</style>